<?php

namespace  Aitels\Foundation\Code;


use Illuminate\Support\Str;

class ClassAnalyser
{

    protected static $psr4;

    public function getHardCodedMethodsReflections($realPath)
    {
        $fileContent = $this->getFileContent($realPath);
        $methods = [];
        foreach ($this->getReflectionMethods($realPath) as $reflectionMethod) {
            $methodName = $reflectionMethod->getName();
            if ($this->isMethodHardCoded($fileContent, $methodName)) {
                $methods[$methodName] = $reflectionMethod;
            }
        }
        return $methods;
    }

    public function getPublicHardCodedMethodsReflections($realPath)
    {
        $fileContent = $this->getFileContent($realPath);
        $methods = [];
        foreach ($this->getReflectionMethods($realPath) as $reflectionMethod) {
            if ($reflectionMethod->isPublic() && !$reflectionMethod->isStatic()) {
                $methodName = $reflectionMethod->getName();
                if ($this->isMethodHardCoded($fileContent, $methodName)) {
                    $methods[$methodName] = $reflectionMethod;
                }
            }
        }
        return $methods;
    }


    protected function isMethodHardCoded($fileContent, $methodName)
    {
        return preg_match("/function\s$methodName/", $fileContent) === 1;
    }


    protected function getReflectionMethods($realPath)
    {
        return (new \ReflectionClass(self::getClassByPath($realPath)))->getMethods();
    }


    protected function getFileContent($realPath)
    {
        return file_get_contents($realPath);
    }


    public static function getClassByPath($realPath)
    {
        $realPath = substr($realPath, 0,-4);
        $realPath=str_replace('\\','/',$realPath);
        foreach (self::getPsr4() as $namespace=>$path){
            $path=str_replace('\\','/',$path);
            if(Str::startsWith($realPath,$path)){
                $class=$namespace.Str::after($realPath,$path);
            }
        }
        $class = str_replace('/', '\\', $class);
        return $class;
    }





    public static function getPsr4()
    {
        if (self::$psr4)
            return self::$psr4;
        $composer = json_decode(file_get_contents(base_path('composer.json')), true);
        $fullPath=[];
        foreach ($composer['autoload']['psr-4'] as $namespace=>$path){
            $fullPath[$namespace]=base_path($path);
        }
        return self::$psr4 = $fullPath;
    }


}
